package com.wxxymaker.controller;

import com.wxxymaker.interceptor.annocation.AuthRequire;
import com.wxxymaker.model.entity.Admin;
import com.wxxymaker.model.entity.Stage;
import com.wxxymaker.service.StageService;
import com.wxxymaker.utils.Const;
import com.wxxymaker.utils.QRCodeUtil;
import com.wxxymaker.utils.web.ResponseWarp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Soft
 * @Date: 2018/5/6 1:01
 * @Desc: 打分阶段控制器
 */
@RestController
@RequestMapping("/stage")
public class StageHandler implements BaseHandler<Stage> {

    @Autowired
    private StageService stageService;

    private HttpServletRequest request;

    @ModelAttribute
    public void init(HttpServletRequest request) {
        this.request = request;
    }

    @PostMapping("/add")
    public ResponseWarp add(Stage stage) {
        Stage add = stageService.add(stage);
        if (null != add) {
            return ResponseWarp.ok(add, "添加成功！");
        }
        return ResponseWarp.error("添加失败！");
    }

    /**
     * 这里可能抛出外键关联，无法删除的异常
     * @param id  要删除的记录id
     */
    @PostMapping("/delete/{id}")
    public ResponseWarp delete(@PathVariable Integer id) {
        Admin admin = (Admin) request.getAttribute("admin");
        if (admin.getGrade() > 1) {
            try {
                Stage stage = stageService.delete(id);
                return ResponseWarp.ok(stage, "删除成功！");
            } catch (Exception e) {
                return ResponseWarp.error("删除失败！该阶段打分进行中！");
            }
        }
        return ResponseWarp.error("删除失败！没有权限！");
    }

    @PostMapping("/change")
    public ResponseWarp change(Stage stage) {
        if (stageService.change(stage)) {
            QRCodeUtil.clear();  // 达到修改过阶段打分公司后 二维码默认全部打分目的
            return ResponseWarp.ok("修改成功！");
        }
        return ResponseWarp.error("修改失败！");
    }

    @AuthRequire
    @PostMapping("/get/{id}")
    public ResponseWarp get(@PathVariable Integer id) {
        Stage one = stageService.getOne(id);
        if (null != one) {
            return ResponseWarp.ok(one, "查询成功！");
        }
        return ResponseWarp.error("查询失败！");
    }

    /**
     * 根据页码和阶段类型查询分页信息
     * @param pageNo 页码
     */
    @AuthRequire
    @PostMapping("/page")
    public ResponseWarp page(@RequestParam(defaultValue = "1") Integer pageNo) {
        Page<Stage> page = stageService.page(pageNo, Const.pageSize);
        if (null != page && page.getTotalElements() > 0) {
            return ResponseWarp.ok(page);
        }
        return ResponseWarp.error("获取分页信息失败!");
    }
}
